package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.NewsAutoScanConstants;
import com.heima.common.constants.WemediaContants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmNewsVo;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author feng js
 */
@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper,WmNews> implements WmNewsService {
    @Value("${fdfs.url}")
    private String fileUrl;
    @Autowired
    KafkaTemplate kafkaTemplate;

    @Autowired
     private WmNewsMaterialMapper newsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //分页条件
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //当前登录id
        if (WmThreadLocalUtils.getUser() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        lambdaQueryWrapper.eq(WmNews::getUserId,WmThreadLocalUtils.getUser().getId());
        //状态条件
        if (dto.getStatus()!=null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //关键字
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //频道列表
        if (dto.getChannelId()!=null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //发布日期
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getSubmitedTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        //排序
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);
        IPage<WmNews> result = page(page, lambdaQueryWrapper);
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) result.getTotal());
        responseResult.setData(result.getRecords());
        responseResult.setHost(fileUrl);
        return responseResult;
    }

    @Override
    public ResponseResult submitNews(WmNewsDto wmNewsDto,Short isSubmit) {
        //检查参数
        if (wmNewsDto == null || wmNewsDto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto,wmNews);
        if (wmNewsDto.getType().equals(WemediaContants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        //dto的map图片转换成String
        String imageStr = wmNewsDto.getImages().toString()
                .replace("[", "")
                .replace("]", "")
                .replace(fileUrl, "").replace(" ","");
        wmNews.setImages(imageStr);
        saveWmNews(wmNews,isSubmit);

        //保存内容图片和文章的关系
       List<String> materials = ectractUrlInfo(wmNews.getContent());
        if (isSubmit.equals(WmNews.Status.SUBMIT.getCode()) && materials.size() > 0) {

         ResponseResult responseResult = saveRelativeInfoForContent(materials,wmNews.getId());

            if (responseResult != null) {
                return responseResult;
            }

        }
        //保存封面图片和文章的关系
        if (isSubmit.equals(WmNews.Status.SUBMIT.getCode())) {
            ResponseResult responseResult = saveRelativeInfoForCover(materials,wmNewsDto,wmNews);
            if (responseResult != null) {
                return responseResult;
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private ResponseResult saveRelativeInfoForCover(List<String> materials, WmNewsDto wmNewsDto, WmNews wmNews) {
        List<String> images = wmNewsDto.getImages();
        if (wmNewsDto.getType().equals(WemediaContants.WM_NEWS_TYPE_AUTO)) {
            if (materials.size() > 0 && materials.size() <= 2) {
                wmNews.setType(WemediaContants.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            } else if (materials.size() > 2) {
                wmNews.setType(WemediaContants.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            } else {
                wmNews.setType(WemediaContants.WM_NEWS_NONE_IMAGE);
            }
            if (images != null && images.size() > 0) {
                String imageStr = StringUtils.join(images.stream().map(x -> x.replace(fileUrl, "")
                        .replace(" ", "")).collect(Collectors.toList()), ",");
                wmNews.setImages(imageStr);
            }
            updateById(wmNews);
        }
        if (images != null) {
            ResponseResult responseResult = saveRelativeInfoForImage(images,wmNews.getId());
            if (responseResult != null) {
                return responseResult;
            }
        }
        return null;
    }

    private ResponseResult saveRelativeInfoForImage(List<String> images,Integer id) {
        images = images.stream().map(x -> x.replace(fileUrl, "").replace(" ", "")).collect(Collectors.toList());
       return saveRelativeInfo(images,id,WemediaContants.WM_COVER_REFERENCE);
    }

    private ResponseResult saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        return saveRelativeInfo(materials,newsId,WemediaContants.WM_CONTENT_REFERENCE);

    }

    private ResponseResult saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials)
                .eq(WmMaterial::getUserId,WmThreadLocalUtils.getUser().getId()));
        if (dbMaterials == null || dbMaterials.size() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"素材失效");
        }
        ArrayList<Integer> materialIds = new ArrayList<>();
        Map<String, Integer> urlIdMap = dbMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        for (String material : materials) {
            Integer materialId = urlIdMap.get(material);
            if (materialId == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "素材失效");
            }
            materialIds.add(materialId);
        }
        newsMaterialMapper.saveRelations(materialIds,newsId,type);
        return null;
    }

    /**
     * 取出内容中的图片
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<String> list = new ArrayList<>();
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {

            if (map.get("type").equals("image")) {
                String imageUrl = (String)map.get("value");
                imageUrl = imageUrl.replace(fileUrl, "");
                list.add(imageUrl);
            }
        }
        return list;
    }

    private void saveWmNews(WmNews wmNews, Short isSubmit) {
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaContants.WM_NEWS_ENABLE_UP);
        wmNews.setStatus(isSubmit);
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        boolean flag = false;
        if (wmNews.getId() != null) {
            //删除文章和素材的对应关系
            newsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            //修改文章表
           flag = updateById(wmNews);
        } else {
            //新增文章
            flag = save(wmNews);
        }
        if (flag) {
            kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC,JSON.toJSONString(wmNews.getId()));
        }
    }

    @Override
    public ResponseResult findById(Integer id) {

        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(fileUrl);
        return responseResult;
    }

    @Override
    public ResponseResult delNewsById(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable().equals(WemediaContants.WM_NEWS_ENABLE_UP)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        newsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto wmNewsDto) {

        if (wmNewsDto == null || wmNewsDto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(wmNewsDto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章未发布，不能上下架");
        }
        if (wmNews.getEnable() != null && wmNews.getEnable() > -1 && wmNews.getEnable() < 2) {
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,wmNews.getId()).set(WmNews::getEnable,wmNewsDto.getEnable()));
        }
        //向文章服务发送修改上下架状态
        if (wmNews.getArticleId() != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("articleId",wmNews.getArticleId());
            map.put("enable",wmNews.getEnable());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询所有状态为4或8的Id；
     * @return
     */
    @Override
    public List<Integer> findRelease() {

        List<WmNews> wmNews = list(Wrappers.<WmNews>lambdaQuery().in(WmNews::getStatus, 4, 8).lt(WmNews::getPublishTime, new Date()));
        if (wmNews == null) {
            return null;
        }
        List<Integer> ids = wmNews.stream().map(WmNews::getId).collect(Collectors.toList());

        return ids;
    }
    @Autowired
    WmNewsMapper wmNewsMapper;

    /**
     * 审核列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        //检查参数
        dto.checkParam();

        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        List<WmNewsVo> list = wmNewsMapper.findList(dto);
        //统计条数
        int count = wmNewsMapper.findListCount(dto);
        //数据封装
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), count);
        responseResult.setData(list);
        responseResult.setHost(fileUrl);
        return responseResult;
    }

    /**
     * 文章审核-查询文章详情
     * @param id
     * @return
     */
    @Autowired
    WmUserService wmUserService;
    @Override
    public ResponseResult findOneNew(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null || wmNews.getUserId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        wmNewsVo.setAuthorName(wmUser.getName());
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(fileUrl);
        return responseResult;
    }

    @Override
    public ResponseResult updateStatus(NewsAuthDto dto,Short status) {

        if (dto.getStatus() == null ||dto.getId()==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        wmNews.setStatus(status);
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }
}
